using System;
using IssueExplorer.Views;

namespace IssueExplorer.Presenters
{
    public abstract class PresenterWithView : Presenter
    {
        private IView view;

        public IView View
        {
            get { return view; }
            set
            {
                if (view != null)
                {
                    DetachViewEventHandler();
                }
                view = value;
                if (view != null)
                {
                    AttachViewEventHandler();
                }
            }
        }

        protected virtual void AttachViewEventHandler()
        {
            View.Close += View_OnClose;
            View.Init += View_OnInit;
        }

        private void View_OnInit(object sender, EventArgs e)
        {
            OnInit();
        }

        private void View_OnClose(object sender, EventArgs e)
        {
            DetachViewEventHandler();
        }

        protected virtual void DetachViewEventHandler()
        {
            View.Close -= View_OnClose;
        }

        protected virtual void OnInit()
        {
        }
    }

    public abstract class PresenterWithView<TView> : PresenterWithView where TView : class, IView
    {
        protected PresenterWithView(TView view)
        {
            View = view;
        }

        public new TView View
        {
            get { return (TView) base.View; }
            set { base.View = value; }
        }
    }
}